package com.controller;

import java.util.ArrayList;
import java.util.List;

import com.common.GlobalPara;
import com.common.base.BaseController;
import com.common.exception.AppException;
import com.common.utils.IdUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.model.Function;
import com.service.FunctionService;

@Before(Tx.class)
public class FunctionController extends BaseController {
	public void enterFunctionManage(){
		List<Function> list = Function.dao.find("select * from function where parentid is null");
		String rootId =list.get(0).getFunctionid();
		setAttr("rootId", rootId);
		render("functionManage.jsp");
	}
	public void getChilderenFuns(){
		String parentId = getPara("parentid");
		List<Function> result;
		if(StrKit.isBlank(parentId)){
			result = new ArrayList<Function>();
		}else{
			result =FunctionService.service.getChilderenFuns(parentId);
		}
		renderJson(result);
	}
	private void setFiledStat(){
		String type = getPara("type");
		String parentid = getPara("parentId");
		Boolean urlDisabled = false;
		Boolean bzDisabled = false;
		Boolean sxDisabled = false;
		//一级菜单
		if(type.equals("1")){
			type = GlobalPara.GNLX_TREE;
			urlDisabled=true;
			bzDisabled = true;
		//二级菜单
		}else if(type.equals("2")){
			type = GlobalPara.GNLX_TREE;
			bzDisabled = true;
		//按钮
		}else{
			urlDisabled=true;
			type = GlobalPara.GNLX_BUTTON;
			sxDisabled=true;
		}
		setAttr("gnlx", type);
		setAttr("urlDisabled",urlDisabled );
		setAttr("bzDisabled", bzDisabled);
		setAttr("sxDisabled", sxDisabled);
		setAttr("parentid", parentid);
	}
	public void enterFunctionAdd(){
		this.setFiledStat();
		render("functionAdd.jsp");
	}
	public void enterFunctionEdit(){
		this.setFiledStat();
		String functionid = getPara("functionid");
		Function fuction  = Function.dao.findById(functionid);
		setAttr("function",fuction);
		render("functionEdit.jsp");
	}
	public void saveFunctionAdd(){
		Function function = getModel(Function.class,"function");
		function.setFunctionid(IdUtil.getId());
		function.save();
		renderSuccess();
	}
	public void deleteFunc(){
		String functionid = getPara("functionid");
		if(StrKit.isBlank(functionid)){
			throw new AppException("请先选中记录后再操作！");
		}
		List<Function> list = FunctionService.service.getChilderenFuns(functionid);
		if(list.size()>0){
			throw new AppException("该菜单下还有子菜单，不能被删除！");
		}
		Function.dao.deleteById(functionid);
		renderSuccess();
	}
	public void saveFunctionEdit(){
		Function function = getModel(Function.class,"function");
		function.update();
		renderSuccess();
	}
}
